package com.sdkj.fixed.asset.assets.controller;

import com.sdkj.fixed.asset.api.assets.AssetInfoChangeApi;
import com.sdkj.fixed.asset.api.assets.in_vo.AssetInfoChangeAssetExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.AssetInfoChangeExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.Params;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.assets.service.AssetChangeService;
import com.sdkj.fixed.asset.assets.util.ExcelStyle;
import com.sdkj.fixed.asset.common.base.BaseResultVo;
import com.sdkj.fixed.asset.common.base.PageBean;
import com.sdkj.fixed.asset.common.base.PageParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author niuliwei
 * @description
 * @date 2020/7/27 11:23
 */
@Controller
public class AssetInfoChangeController implements AssetInfoChangeApi {
    @Autowired
    private AssetChangeService service;
    @Autowired
    private HttpServletResponse response;

    @Override
    public BaseResultVo add(AssetInfoChangeExtend change) {
        service.add(change);
        return BaseResultVo.success(change.getId());
    }

    @Override
    public BaseResultVo getAllPage(PageParams<SelPrams> param) {
        List<AssetInfoChangeExtend> list = service.getAllPage(param);
        PageBean pageBean = new PageBean(list);
        return BaseResultVo.success(pageBean);
    }

    @Override
    public BaseResultVo selById(Params params) {
        AssetInfoChangeExtend extend = service.selById(params.getId());
        return BaseResultVo.success(extend);
    }

    @Override
    public void print(String id) throws IOException {
        AssetInfoChangeExtend extend = service.print(id);
        String title = "资产实物信息变更单";
        String sheetName = "资产实物信息变更";
        String fileName = "资产实物信息变更单";

//        创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFRow row = null;
        HSSFCell cell = null;
        int rownum = 0;
        // 建立新的sheet对象（excel的表单） 并设置sheet名字
        HSSFSheet sheet = wb.createSheet(sheetName);
        ExcelStyle.printSetup(sheet);
        sheet.setDefaultColumnWidth(16);
        sheet.setColumnWidth(0, 256 * 6);
        sheet.setDefaultRowHeight((short) 512);

        // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        row = sheet.createRow(rownum++);
        row.setHeight((short) 1000 );
        // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        cell = row.createCell(1);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
        cell.setCellValue(title);
        cell.setCellStyle(ExcelStyle.styleTitle(wb));

        String source = extend.getSource();//"购入",2"自建",3"租赁",4"捐赠",5"其他",6"内部购入"'
        if(StringUtils.isBlank(source)){
            source = "";
        } else {
            switch (source) {
                case "1":
                    source = "购入";
                    break;
                case "2":
                    source = "自建";
                    break;
                case "3":
                    source = "租赁";
                    break;
                case "4":
                    source = "捐赠";
                    break;
                case "5":
                    source = "其他";
                    break;
                case "6":
                    source = "内部购入";
                    break;
                default:
                    source = "";
                    break;
            }
        }

        String[] row1 = {"变更单号：", extend.getNumber(), "", "","业务日期：", extend.getDate(), "操作员：", extend.getHandleUserName()};
        String[] row2 = {"变更内容：", "", "", "", "", "", "", ""};
        String[] row3 = {"资产类别：", extend.getClassName(), "", "", "资产名称：", extend.getAssetName(), "规格型号：",extend.getSpecificationModel()};
        String[] row4 = {"SN号：", extend.getSnNumber(), "", "", "计量单位：", extend.getUnitMeasurement(), "购入日期：", extend.getPurchaseTime()};
        String[] row5 = {"使用期限（月）：", extend.getServiceLife(), "", "", "使用公司：", extend.getUseCompanyName(), "使用部门：",extend.getUseDepartmentName()};
        String[] row6 = {"使用人：", extend.getUserName(), "", "", "区域：", extend.getAreaName(), "存放地点：",extend.getStorageLocation()};
        String[] row7 = {"备注：", extend.getRemark(), "", "", "来源：", source, "供应商名称：",extend.getSupplierName()};
        String[] row8 = {"变更明细："};
        String[] row9 = {"序号","资产编码","资产名称","变更前所属公司","变更前所属部门","变更前使用人","变更前区域","变更前存放地点"};

        List<String[]> rowList = new ArrayList<>();
        rowList.add(row1);
        rowList.add(row2);
        rowList.add(row3);
        rowList.add(row4);
        rowList.add(row5);
        rowList.add(row6);
        rowList.add(row7);
        rowList.add(row8);
        rowList.add(row9);

        for (String[] rows : rowList) {
            row = sheet.createRow(rownum++);
            for (int i = 0; i < rows.length; i++) {
                cell = row.createCell(i + 1);
                cell.setCellValue(rows[i]);
                if(rownum == 3 || rownum == 9){
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 3));
                    row.setHeight((short)700);
                } else if (rownum == 10){
                    cell.setCellStyle(ExcelStyle.styleCellName(wb));
                } else {
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 2));
                }

            }
        }

        //遍历数据
        int j = 1;
        for (AssetInfoChangeAssetExtend result : extend.getInfoChangeAssetExtendList()) {
            row = sheet.createRow(rownum++);
            String[] cells = {"", result.getAssetCode(), result.getAssetName(), result.getUseCompanyName(), result.getUseDepartmentName(), result.getHandlerUser(),result.getAreaName(), result.getStorageLocation()};
            for (int i = 0; i < cells.length; i++) {
                cell = row.createCell(i + 1);
                if(i==0){
                    cell.setCellValue(j++);
                } else {
                    cell.setCellValue(cells[i]);
                }
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
            }
        }

        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition","attachment; filename="+ URLEncoder.encode(fileName + ".xlsx", "UTF-8"));    //filename =  文件名
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }
}
